#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::to_string;

class HasPtr {
    friend void swap(HasPtr&, HasPtr&);
public:
    HasPtr(const string s = string()) :
        ps(new string(s)), i(0) {   }
    HasPtr(const HasPtr &p) :
        ps(new string(*p.ps)), i(p.i) { }   // 拷贝构造函数
    HasPtr& operator =(const HasPtr &); // 拷贝赋值运算符
    HasPtr& operator =(const string &); // 赋予新 string
    string& operator *();   // 解引用
    bool operator <(const HasPtr&) const;  // 比较运算符
    ~HasPtr();  // 析构函数
private:
    string *ps;
    int i;
};

HasPtr::~HasPtr()
{
    delete ps;
}

HasPtr& HasPtr::operator =(const HasPtr &rhs)
{
    auto newp = new string(*rhs.ps);
    delete ps;
    ps = newp;
    i = rhs.i;
    return *this;
}

HasPtr& HasPtr::operator =(const string &rhs)
{
    *ps = rhs;
    return *this;
}

string& operator *()
{
    return *ps;
}

inline void swap(HasPtr &lhs, HasPtr &rhs)
{
    using namespace std;
    cout << "交换" << *lhs.ps << "和" << *rhs.ps << endl;
    swap(lhs.ps, rhs.ps);
    swap(lhs.i, rhs.i);
}

bool operator <(const HasPtr &rhs) const
{
    return *ps < *rhs.ps;
}

void test_13_31()
{
    vector<HasPtr> vh;
    int n = atoi("11");
    for (int i = 0; i < n; i++) {
        vh.push_back(to_string(n - i));
    }
    for (auto p : vh) {
        cout << *p << " ";
    }
    cout << endl;
    sort(vh.begin(), vh.end());
    for (auto p : vh) {
        cout << *p << " ";
    }
    cout << endl;
}
